import { memo, useMemo, useRef } from 'react'
import styles from './index.module.scss'
import { useNavigate, useParams } from 'react-router-dom'
import { Space, Button, Typography, Input, Tooltip, InputRef, message, Popover } from 'antd'
import { CopyOutlined, LeftOutlined, QrcodeOutlined } from '@ant-design/icons'
import { QRCodeSVG } from 'qrcode.react'

const { Title } = Typography

type PropsType = {
  title: string
  isPublish: boolean | undefined
}

const StaticHeader = memo(({ title, isPublish }: PropsType) => {
  const nav = useNavigate()
  const { id } = useParams()

  //拷贝链接
  const urlInputRef = useRef<InputRef>(null)
  function copy() {
    const elem = urlInputRef?.current
    if (elem == null) return
    elem.select() //选中 input 的内容
    document.execCommand('copy') //拷贝选中内容
    message.success('拷贝成功!')
  }

  //使用useMemo 1.依赖项不经常变化 2.缓存的元素是否创建成本较高
  const genLinkAndQRCodeElem = useMemo(() => {
    if (!isPublish) return null

    //拼接 url 需要参考 C 端的规则
    const url = `http://localhost:5174/question/${id}`

    //定义二维码组件
    const QRCodeElem = (
      <div style={{ textAlign: 'center' }}>
        <QRCodeSVG value={url} size={150} />
      </div>
    )

    return (
      <Space>
        <Input ref={urlInputRef} value={url} style={{ width: '300px' }} />
        <Tooltip title="拷贝链接">
          <Button icon={<CopyOutlined />} onClick={copy}></Button>
        </Tooltip>
        <Popover content={QRCodeElem}>
          <Button icon={<QrcodeOutlined />} onClick={copy}></Button>
        </Popover>
      </Space>
    )
  }, [id, isPublish])

  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <Title>{title}</Title>
          </Space>
        </div>
        <div className={styles.center}>{genLinkAndQRCodeElem}</div>
        <div className={styles.right}>
          <Button type="primary" onClick={() => nav(`/question/edit/${id}`)}>
            编辑问卷
          </Button>
        </div>
      </div>
    </div>
  )
})

export default StaticHeader
